;
(function() {
  let canvas = document.querySelector("#canvas");
  let ctx = canvas.getContext("2d");
  let mouseDrag = false;
  let mouseStatus = 1; // 1 = "draw" || 2 = "earser"
  // 修改线条粗细
  let lineWidth = 2;
  let lineColor = "rgb(32, 128, 205)";

  canvas.addEventListener("mousedown", function(e) {
    mouseDrag = true;
    ctx.moveTo(e.offsetX, e.offsetY);
    console.log("mousedown");
  })
  canvas.addEventListener("mouseup", function(e) {
    mouseDrag = false;
    console.log("mouseup");
  })
  canvas.addEventListener("mousemove", function(e) {
    if (mouseDrag && mouseStatus === 1) {
      ctx.globalCompositeOperation = "source-over";
    } else if (mouseDrag && mouseStatus === 2) {
      ctx.globalCompositeOperation = "destination-out"
    }
    if (mouseDrag) {
      ctx.lineWidth = lineWidth;
      ctx.lineJoin = "round";
      ctx.lineTo(e.offsetX, e.offsetY);
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(e.offsetX, e.offsetY, lineWidth / 2, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.moveTo(e.offsetX, e.offsetY);
    }
    console.log(mouseStatus);
  })

  $(".mode-item").click(function() {
    $(this).addClass("active").siblings().removeClass('active');
    console.log($(this).data("type"));
    mouseStatus = $(this).data("type");
  })

  $(".line-item").click(function() {
    $(this).addClass("active").siblings().removeClass('active');
    console.log($(this).data("width"));
    lineWidth = $(this).data("width");
  })

  $(".color-item").click(function() {
    $(".line-item").css("background-color", $(this).css("background-color"))
    console.log($(this).css("background-color"));
    lineColor = $(this).css("background-color");
    ctx.strokeStyle = lineColor;
    ctx.fillStyle = lineColor;
  })

  $(".trash").click(function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  })

  function init() {
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.fillStyle = lineColor;
  }
  init();
})();
